package com.qfedu.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {

    // 获取mybatis 链接
    public static SqlSession getSqlSession()  {


        // 读取mybatis "mybatisConfig.xml"
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatisConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 工厂辅助类，帮助初始化 工厂   SqlSessionFactoryBuilder 建造者模式
        SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();

        //SqlSessionFactory  SqlSession 工厂，工厂设计模式
        SqlSessionFactory sqlSessionFactory = sessionFactoryBuilder.build(inputStream);

        // 创建sql 连接 相当于 jdbc connection
        //  sqlSessionFactory.openSession(); 默认情况下 是关闭自动提交，开启事务
        // sqlSessionFactory.openSession(true); 开启自动提交  关闭事务
        SqlSession sqlSession =  sqlSessionFactory.openSession(true);

        return sqlSession;
    }

}
